package com.yanqu.road.server.cmd.cross.player;

import com.yanqu.road.entity.manor.ManorHelpResult;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.manor.ManorProto;
import com.yanqu.road.server.cmd.base.AbstractServerCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.manor.ManorMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.PropertyHelper;

@Cmd(code = Protocol.S_CROSS_MANOR_HELP, desc = "跨服庄园互助")
public class CrossManorHelpPlayerCmd extends AbstractServerCommand {

	private long userId;
	private UserBaseInfo userBaseInfo;
	private long helpUserId;

	private ManorHelpResult manorHelpResult;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		ManorProto.CrossHelpPlayerReqMsg reqMsg = ManorProto.CrossHelpPlayerReqMsg.parseFrom(packet.getBytes());
		userId = reqMsg.getUserId();
		userBaseInfo = PlayerBasePb.parseToUserBaseInfo(reqMsg.getPlayerBaseData());
		helpUserId = reqMsg.getHelpUserId();
		return true;
	}

	@Override
	public void execute(YanQuMessage packet) throws Exception {
		GamePlayer helpPlayer = GamePlayerMgr.getOnlinePlayer(helpUserId);
		if (null != helpPlayer) {
			synchronized (ManorMgr.checkLockObj) {
				manorHelpResult = ManorMgr.onlineManorHelp(userId, userBaseInfo, true, null, helpPlayer, helpUserId);
			}
		} else {
			synchronized (ManorMgr.offLineCheckLockObj) {
				manorHelpResult = ManorMgr.offlineManorHelp(userId, userBaseInfo, true, null, helpUserId);
			}
		}
	}

	@Override
	public void sendData(YanQuMessage packet) throws Exception {
		ManorProto.CrossHelpPlayerRespMsg.Builder respMsg = ManorProto.CrossHelpPlayerRespMsg.newBuilder();
		respMsg.setUserId(userId);
		respMsg.setServerId(userBaseInfo.getServerId());
		respMsg.setHelpUserId(helpUserId);
		respMsg.setRet(manorHelpResult.getRet());
		if(0 == manorHelpResult.getRet()){
			respMsg.setReward(PropertyHelper.parsePropertyToString(manorHelpResult.getReward()));
			respMsg.setHelpCount(manorHelpResult.getManorHelpCount());
		}
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_MANOR_HELP_PLAYER_RESP, respMsg);
		GamePlayerMgr.sendPacket(0, pbMsg);
	}
}
